package xyz.itpath.gen.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import xyz.itpath.gen.dto.Column;
import xyz.itpath.gen.dto.Table;
import xyz.itpath.gen.service.GeneratorService;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate;
import java.util.List;

/**
 * @author zhaom
 * @date 2021/9/22 - 17:44
 */
@Controller
@RequestMapping("/itpath")
public class GeneratorController {

    private final GeneratorService generatorService;

    public GeneratorController(GeneratorService generatorService) {
        this.generatorService = generatorService;
    }

    @GetMapping("/list/table")
    public String listTable(Model model) {
        List<Table> tables = generatorService.listAllTable();
        model.addAttribute("tables", tables);
        return "ui/list_table";
    }

    @ResponseBody
    @GetMapping("/list/col")
    public List<Column> listColumn(@RequestParam String dbName,
                                   @RequestParam String tbName) {
        return generatorService.listColumns(dbName, tbName);
    }

    @GetMapping("/gen")
    public void genCode(@RequestParam String dbName,
                        @RequestParam String tbName,
                        @RequestParam String bkName,
                        HttpServletResponse response) throws IOException {
        response.setHeader("content-disposition", "attachment;filename=" + LocalDate.now().toString());
        generatorService.genCode(dbName, tbName, bkName, response.getOutputStream());
    }
}
